/*var the_flow_id = '4';*/
var urlHeader = localStorage.getItem('host') + "manager/";

//节点表单
var urlList = {
    queryAllFormFields: "queryAllFormFields.do",
    insertNodeFromInfo: "insertNodeFromInfo.do",
    queryNodeFromInfoAllByNodeId: "queryNodeFromInfoAllByNodeId.do",
    queryNodeFromByNodeId: "queryNodeFromByNodeId.do",
    isProductWork: "isProductWork.do"
    //updateNodeFromInfo:"updateNodeFromInfo.do"
}

var isExisted = false;  //判断该流程是否已经保存过

//弹窗方法
var popup = {
    //表单验证弹出框部分
    timeErr: {time: ''},
    timeSuc: {time: ''},
    timeI: {time: ''},

    animations: function (ele, time ,appearTime) {
        clearTimeout(time.time)
        $('.' + ele, parent.document).animate({
            'right': '48px',
        }, appearTime || 500, function () {
            //time.time = setTimeout(function () {
                $('.' + ele, parent.document).css({'right': '-250px'})
                $('.' + ele, parent.document).css('display', 'none')
            //}, disappearTime || 3000)
        })
    },
    Message: function (ele, mes ,appearTime) {
        var element = null
        if (ele == 'T') element = 'sucMes'
        else if (ele == 'F') element = 'errMes'
        else if (ele == 'I') element = 'IMes'
        $('.' + element, parent.document).html(mes)
        if (element == 'errMes') {
            $('.mesFalse', parent.document).css('display', 'block')
            this.animations('mesFalse', this.timeErr, appearTime)
        }
        if (element == 'sucMes') {
            $('.mesTrue', parent.document).css('display', 'block')
            this.animations('mesTrue', this.timeSuc ,appearTime)
        }
        if (element == 'IMes') {
            $('.mesI', parent.document).css('display', 'block')
            this.animations('mesI', this.timeI ,appearTime)
        }
    }
};


function fillNodeFrom(activeId) {
    $.ajax({
        url: urlHeader + urlList.queryNodeFromByNodeId,
        type: 'POST',
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        data: {
            node_id: activeId
        },
        success: function (data) {
            data = JSON.parse(data)
            $.each(data.content, function (i, e) {
                if (e.define_id) {
                    $('.customShow[data-type="2"][define_id=' + e.define_id + ']').prop("checked", true);
                    $('.customShow[data-type="4"][define_id=' + e.define_id + ']').prop("checked", true);
                    if (e.is_edit == 1) {
                        $(".customShow[define_id=" + e.define_id + "]").parents('tr').find('.edit').prop("checked", true)
                    }
                }
                else if (e.fixed_key) {
                    $('.customShow[data-type="1"][define_id=' + e.fixed_key + ']').prop("checked", true);
                    $('.customShow[data-type="5"][define_id=' + e.fixed_key + ']').prop("checked", true);
                    if (e.is_edit == 1) {
                        $(".customShow[define_id=" + e.fixed_key + "]").parents('tr').find('.edit').prop("checked", true)
                    }
                }
            })
            $(".customShow:checked").parents('tr').find('.edit').prop('disabled', false)
        }
    })
}


function initialCheckbox() {
    $(".customShow").prop("checked", false);
    $(".customShow").prop("checked", false);
    $(".edit").prop("checked", false).prop("disabled", true);
}

//var urlHeader = "http://10.156.0.209:8088/ks_manager/manager/";
/*页面回调执行    callbackSuperDialog
    if(window.ActiveXObject){ //IE
        window.returnValue = globalValue
    }else{ //非IE
        if(window.opener) {
            window.opener.callbackSuperDialog(globalValue) ;
        }
    }
    window.close();
*/
function callbackSuperDialog(selectValue) {
    var aResult = selectValue.split('@leipi@');
    $('#' + window._viewField).val(aResult[0]);
    $('#' + window._hidField).val(aResult[1]);
    //document.getElementById(window._hidField).value = aResult[1];
}

/* 获取页面参数 */
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = top.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return r[2];
    return null; //返回参数值
}

function getAurlparam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var sname = top.location.search;
    var name1 = decodeURIComponent(top.location.search);
    if (sname == name1) {
        this.fn.Message("F", "路径不合法");
    }
    else {
        var r = decodeURIComponent(top.location.search).substr(1).match(reg);
        if (r != null) return r[2];
        return null; //返回参数值
    }
}

/**
 * 弹出窗选择用户部门角色
 * showModalDialog 方式选择用户
 * URL 选择器地址
 * viewField 用来显示数据的ID
 * hidField 隐藏域数据ID
 * isOnly 是否只能选一条数据
 * dialogWidth * dialogHeight 弹出的窗口大小
 */
function superDialog(URL, viewField, hidField, isOnly, dialogWidth, dialogHeight) {
    dialogWidth || (dialogWidth = 620)
        , dialogHeight || (dialogHeight = 520)
        , loc_x = 500
        , loc_y = 40
        , window._viewField = viewField
        , window._hidField = hidField;
    // loc_x = document.body.scrollLeft+event.clientX-event.offsetX;
    //loc_y = document.body.scrollTop+event.clientY-event.offsetY;
    if (window.ActiveXObject) { //IE
        var selectValue = window.showModalDialog(URL, self, "edge:raised;scroll:1;status:0;help:0;resizable:1;dialogWidth:" + dialogWidth + "px;dialogHeight:" + dialogHeight + "px;dialogTop:" + loc_y + "px;dialogLeft:" + loc_x + "px");
        if (selectValue) {
            callbackSuperDialog(selectValue);
        }
    } else {  //非IE
        var selectValue = window.open(URL, 'newwindow', 'height=' + dialogHeight + ',width=' + dialogWidth + ',top=' + loc_y + ',left=' + loc_x + ',toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no');

    }
}


$(function () {
    var alertModal = $('#alertModal'), attributeModal = $("#attributeModal");
    //消息提示
    mAlert = function (messages, s) {
        if (!messages) messages = "";
        if (!s) s = 2000;
        alertModal.find(".modal-body").html(messages);
        alertModal.modal('toggle');
        setTimeout(function () {
            alertModal.modal("hide")
        }, s);
    }

    //属性设置
    attributeModal.on("hidden", function () {
        $(this).removeData("modal");//移除数据，防止缓存
    });
    ajaxModal = function (url, fn) {
        url += url.indexOf('?') ? '&' : '?';
        url += '_t=' + new Date().getTime();
        attributeModal.modal('toggle');

        //加载完成执行
        if (fn) {
            attributeModal.on('shown', fn);
        }
    }

    //刷新页面
    function page_reload() {
        location.reload();
    }

    function getUuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("").substr(0, 8);
        return uuid;
    }

    /*
    php 命名习惯 单词用下划线_隔开
    js 命名习惯：首字母小写 + 其它首字线大写
    */
    /*var processNames = {
        list:[
            { id : 1 , process_name:"aaaa"}
        ]
    }*/
    /*步骤数据*/
    var processData;
    var product_id = getAurlparam('productId');
    var workflow_id = getAurlparam('workflowId');
    var product_name = decodeURI(getAurlparam('productName'));
    var products = {};

    $.ajax({
        url: urlHeader + "queryNodeInfoByPIdAndWId.do",
        async: false,
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        data: {product_id: product_id, workflow_id: workflow_id},
        type: "POST",
        success: function (data) {
            data = JSON.parse(data)
            if (data.type == 1) {
                processData = data;
                var list = processData.content.flow;
                for (var i = 0; i < list.length; i++) {
                    var v = list[i];
                    products[v.id] = v;
                }
            } else {
                processData = {};
            }
        }, error: function () {

        }
    });

    $.ajax({
        url: urlHeader + urlList.isProductWork,
        async: false,
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        data: {product_id: product_id, workflow_id: workflow_id},
        type: "POST",
        success: function (data) {
            data = JSON.parse(data);
            if (data.type == 1) {
                isExisted = true;
                //$("#leipi_save_all").removeClass('btn-info').addClass('btn-inverse');
            }else{

            }
        }
    })

    $("#leipi_save_all").on('click', function () {

        /*var _canvas = $("#flowdesign_canvas").Flowdesign({
            "processData": processData
            /!*,mtAfterDrop:function(params)
            {
                //popup.Message("T","连接："+params.sourceId +" -> "+ params.targetId);
            }*!/
            /!*画面右键*!/
            , canvasMenus: {
                "cmAdd": function (t) {

                }}})*/
        function deployProccAction() {
            $.ajax({
                url: urlHeader + "deployProcc.do",
                crossDomain: true,
                xhrFields: {
                    withCredentials: true
                },
                data: {
                    deployName: product_name,
                    workflow_id: workflow_id,
                    product_id: product_id
                },
                type: "POST",
                success: function (data) {
                    data = JSON.parse(data)
                    if (data.type == 1) {
                        popup.Message("T", data.msg ,300 ,0)
                        setTimeout(function(){
                            history.go(-1);
                        },300)
                    } else {
                        popup.Message("F", data.msg)
                    }
                    /*location.href="/ks_manager/order.html";*/
                }
            })
        }

        var processInfo = _canvas.getProcessInfo(product_id, workflow_id, product_name);//连接信息
        //processNames
        /*重要提示 start*/
        /* popup.Message("T","这里使用ajax提交，请参考官网示例，可使用Fiddler软件抓包获取返回格式");*/
        /*重要提示 end */

        //判断是否选择了审批角色
        var flag = true;
        $.each(processInfo.nodeList, function (index, item) {
            if (!item.role_id) {
                popup.Message("I", '请选择角色')
                flag = false;
                return false;
            }
        })

        if (!processInfo.isOk) {
            popup.Message("I", "请连线后在保存信息");
            return false;
        }
        ;

        if (flag) {
            $.ajax({
                url: urlHeader + "defWorkflow.do",
                crossDomain: true,
                xhrFields: {
                    withCredentials: true
                },
                data: {
                    frontData: JSON.stringify(processInfo)
                },
                type: "POST",
                success: function (data) {
                    data = JSON.parse(data)
                    if (data.type == 1) {
                        deployProccAction();
                    }
                }
            });
        }
    })


    /*创建流程设计器*/
        var _canvas = $("#flowdesign_canvas").Flowdesign({
            "processData": processData
            /*,mtAfterDrop:function(params)
            {
                //popup.Message("T","连接："+params.sourceId +" -> "+ params.targetId);
            }*/
            /*画面右键*/
            , canvasMenus: {
                "cmAdd": function (t) {

                    //var mLeft = parseInt($("#jqContextMenu").css("left")) / parseInt($(window).width()) * 100 + '%',
                    //mTop = parseInt($("#jqContextMenu").css("top")) / parseInt($(window).height()) * 100 + '%';
                    var mLeft = parseInt($("#jqContextMenu").css("left")),
                        mTop = parseInt($("#jqContextMenu").css("top"));



                    /*重要提示 start*/
                    /*
                                        popup.Message("T","这里使用ajax提交，请参考官网示例，可使用Fiddler软件抓包获取返回格式");
                    */
                    //var style = "width:121px;height:41px;line-height:41px;color:#0e76a8;left:" + mLeft + ";top:" + mTop + ";";
                    var style = "width:121px;height:41px;line-height:41px;color:#0e76a8;left:" + mLeft + "px;top:" + mTop + "px;";
                    $.ajax({
                        url: urlHeader + "insertNodeInfo.do",
                        crossDomain: true,
                        xhrFields: {
                            withCredentials: true
                        },
                        data: {style: style, workflow_id: workflow_id, product_id: product_id},
                        type: 'POST',
                        //将修改的样式以及查询返回的数据传入addProcess
                        success: function (data) {
                            _canvas.addProcess(JSON.parse(data), style)
                        }
                    });
                },
                "cmSave": function (t) {

                    //定义方法
                    function deployProccAction() {
                        $.ajax({
                            url: urlHeader + "deployProcc.do",
                            crossDomain: true,
                            xhrFields: {
                                withCredentials: true
                            },
                            data: {
                                deployName: product_name,
                                workflow_id: workflow_id,
                                product_id: product_id
                            },
                            type: "POST",
                            success: function (data) {
                                data = JSON.parse(data)
                                if (data.type == 1) {
                                    popup.Message("T", data.msg ,300 , 0)
                                    setTimeout(function(){
                                        history.go(-1);
                                    },300)
                                } else {
                                    popup.Message("F", data.msg)
                                }
                            }
                        })
                    }

                    var processInfo = _canvas.getProcessInfo(product_id, workflow_id, product_name);//连接信息
                    //processNames
                    /*重要提示 start*/
                    /* popup.Message("T","这里使用ajax提交，请参考官网示例，可使用Fiddler软件抓包获取返回格式");*/
                    /*重要提示 end */

                    //判断是否选择了审批角色
                    var flag = true;

                    /*if(isExisted){
                        popup.Message("I",'流程已保存，无法再次保存');
                        return false;
                    }*/

                    $.each(processInfo.nodeList, function (index, item) {
                        if (!item.role_id) {
                            popup.Message("I", '请选择角色')
                            flag = false;
                            return false;
                        }
                    })

                    if (!processInfo.isOk) {
                        popup.Message("I", "请连线后在保存信息");
                        return false;
                    }
                    ;

                    if (flag) {
                        $.ajax({
                            url: urlHeader + "defWorkflow.do",
                            crossDomain: true,
                            xhrFields: {
                                withCredentials: true
                            },
                            data: {
                                frontData: JSON.stringify(processInfo)
                            },
                            type: "POST",
                            success: function (data) {
                                data = JSON.parse(data)
                                if (data.type == 1) {
                                    deployProccAction();
                                }
                            }
                        });
                    }
                },
                //刷新
                "cmRefresh": function (t) {
                    location.reload();//_canvas.refresh();
                },
                /*"cmPaste": function(t) {
                    var pasteId = _canvas.paste();//右键当前的ID
                    if(pasteId<=0)
                    {
                      popup.Message("T","你未复制任何步骤");
                      return ;
                    }
                    popup.Message("T","粘贴:" + pasteId);
                },*/
                "cmHelp": function (t) {
                    mAlert('<ul><li><a href="http://flowdesign.leipi.org/doc.html" target="_blank">流程设计器 开发文档</a></li><li><a href="http://formdesign.leipi.org/doc.html" target="_blank">表单设计器 开发文档</a></li><li><a href="http://formdesign.leipi.org/demo.html" target="_blank">表单设计器 示例DEMO</a></li></ul>', 20000);
                }

            }
            /*步骤右键*/
            , processMenus: {
                /*
                "pmBegin":function(t)
                {
                    var activeId = _canvas.getActiveId();//右键当前的ID
                    popup.Message("T","设为第一步:"+activeId);
                },
                "pmAddson":function(t)//添加子步骤
                {
                      var activeId = _canvas.getActiveId();//右键当前的ID
                },
                "pmCopy":function(t)
                {
                    //var activeId = _canvas.getActiveId();//右键当前的ID
                    _canvas.copy();//右键当前的ID
                    popup.Message("T","复制成功");
                },*/
                "pmDelete": function (t) {

                    $(".processDelete_winBox").toggle();


                    $("#sureDel").unbind().on("click", function () {

                        var activeId = _canvas.getActiveId();//右键当前的ID

                        $.ajax({
                            url: urlHeader + "delNodeById.do",
                            crossDomain: true,
                            xhrFields: {
                                withCredentials: true
                            },
                            data: {node_id: activeId},
                            type: "POST",
                            success: function (data) {
                                location.reload();
                            }
                        });

                        /*$.post(url, { node_id: activeId, workflow_id: workflow_id }
                        , function (data) {
                            location.reload();
                            /!*if (data.status == 1) {
                                //清除步骤
                                _canvas.delProcess(activeId);
                                //清除连接   暂时先保存设计 + 刷新 完成
                                var processInfo = ProcessInfo;//连接信息
                                var url = "";
                                $.post(url, {"flow_id": the_flow_id, "process_info": processInfo}, function (data) {
                                    location.reload();
                                }, 'json');

                            }*!/
                            /!*mConstant.fn.Message("F",data.msg);*!/
                        });*/
                    })

                    $("#canDel").unbind().on("click", function () {
                        $(".processDelete_winBox").toggle();
                    })

                    $(".headerIcon").unbind().on("click", function () {
                        $(".processDelete_winBox").toggle();
                    })
                },
                "pmAttribute": function (t) {
                    var activeId = _canvas.getActiveId();//右键当前的ID
                    /*重要提示 start*/
                    /*popup.Message("T","这里要使用程序处理，并非简单html页面，如果无法显示，请建立虚拟站点");*/
                    /*重要提示 end */
                    //var url = "/index.php?s=/Flowdesign/attribute/id/"+activeId+".html";
                    var url = '/ks_manager/login/attribute.html?id=' + activeId;
                    var process_name = $("#window" + activeId).find('.text').text();
                    var role_id = $("#window" + activeId).attr('role_id');
                    var approvalType = $("#window" + activeId).attr('approvalType') ? $("#window" + activeId).attr('approvalType') : '1';

                    //初始化弹框里的值
                    /*if(products[activeId]){
                        var v = products[activeId];
                        $("#process_name").val(v.node_name);
                        $('#role_select option[value=' + v.role_id + ']').attr('selected',false).attr('selected',true);
                    }else{*/
                    $("#process_name").val(process_name);
                    if (!role_id) {
                        $('#role_select option').eq(0).prop('selected', false).prop('selected', true);
                    }
                    else {
                        $('#role_select option[value=' + role_id + ']').prop('selected', false).prop('selected', true);
                    }
                    //}
                    $('input[name="roamTaskPeople"][value=' + approvalType + ']').prop('checked', true);


                    //在勾选前初始化一下
                    initialCheckbox();

                    //将勾选的再次选中，填写真实数据
                    fillNodeFrom(activeId);

                    ajaxModal(url, function () {
                        //popup.Message("T",'加载完成执行')
                    });
                },
                "pmForm": function (t) {
                    var activeId = _canvas.getActiveId();//右键当前的ID
                    /*重要提示 start*/
                    /*popup.Message("T","这里要使用程序处理，并非简单html页面，如果无法显示，请建立虚拟站点");*/
                    /*重要提示 end */
                    //var url = "/index.php?s=/Flowdesign/attribute/id/"+activeId+".html";
                    var url = '/ks_manager/login/attribute.html?id=' + activeId;
                    var process_name = $("#window" + activeId).find('.text').text();
                    var role_id = $("#window" + activeId).attr('role_id');
                    var approvalType = $("#window" + activeId).attr('approvalType') ? $("#window" + activeId).attr('approvalType') : '1';

                    //初始化弹框里的值
                    /*if(products[activeId]){
                        var v = products[activeId];
                        $("#process_name").val(v.node_name);
                        $('#role_select option[value=' + v.role_id + ']').attr('selected',false).attr('selected',true);
                    }else{*/
                    $("#process_name").val(process_name);
                    if (!role_id) {
                        $('#role_select option').eq(0).prop('selected', false).prop('selected', true);
                    }
                    else {
                        $('#role_select option[value=' + role_id + ']').prop('selected', false).prop('selected', true);
                    }
                    //}
                    $('input[name="roamTaskPeople"][value=' + approvalType + ']').prop('checked', true);


                    //在勾选前初始化一下
                    initialCheckbox();

                    //将勾选的再次选中，填写真实数据
                    fillNodeFrom(activeId);

                    ajaxModal(url, function () {
                        //popup.Message("T",'加载完成执行')
                    });
                },
                "pmJudge": function (t) {
                    var activeId = _canvas.getActiveId();//右键当前的ID
                    /*重要提示 start*/
                    /*popup.Message("T","这里要使用程序处理，并非简单html页面，如果无法显示，请建立虚拟站点");*/
                    /*重要提示 end */
                    //var url = "/index.php?s=/Flowdesign/attribute/id/"+activeId+".html";
                    var url = '/ks_manager/login/attribute.html?id=' + activeId;
                    var process_name = $("#window" + activeId).find('.text').text();
                    var role_id = $("#window" + activeId).attr('role_id');
                    var approvalType = $("#window" + activeId).attr('approvalType') ? $("#window" + activeId).attr('approvalType') : '1';

                    //初始化弹框里的值
                    /*if(products[activeId]){
                        var v = products[activeId];
                        $("#process_name").val(v.node_name);
                        $('#role_select option[value=' + v.role_id + ']').attr('selected',false).attr('selected',true);
                    }else{*/
                    $("#process_name").val(process_name);
                    if (!role_id) {
                        $('#role_select option').eq(0).prop('selected', false).prop('selected', true);
                    }
                    else {
                        $('#role_select option[value=' + role_id + ']').prop('selected', false).prop('selected', true);
                    }
                    //}
                    $('input[name="roamTaskPeople"][value=' + approvalType + ']').prop('checked', true);


                    //在勾选前初始化一下
                    initialCheckbox();

                    //将勾选的再次选中，填写真实数据
                    fillNodeFrom(activeId);

                    ajaxModal(url, function () {
                        //popup.Message("T",'加载完成执行')
                    });
                },
                "pmSetting": function (t) {
                    var activeId = _canvas.getActiveId();//右键当前的ID
                    /*重要提示 start*/
                    /*popup.Message("T","这里要使用程序处理，并非简单html页面，如果无法显示，请建立虚拟站点");*/
                    /*重要提示 end */
                    //var url = "/index.php?s=/Flowdesign/attribute/id/"+activeId+".html";
                    var url = '/ks_manager/login/attribute.html?id=' + activeId;
                    var process_name = $("#window" + activeId).find('.text').text();
                    var role_id = $("#window" + activeId).attr('role_id');
                    var approvalType = $("#window" + activeId).attr('approvalType') ? $("#window" + activeId).attr('approvalType') : '1';

                    //初始化弹框里的值
                    /*if(products[activeId]){
                        var v = products[activeId];
                        $("#process_name").val(v.node_name);
                        $('#role_select option[value=' + v.role_id + ']').attr('selected',false).attr('selected',true);
                    }else{*/
                    $("#process_name").val(process_name);
                    if (!role_id) {
                        $('#role_select option').eq(0).prop('selected', false).prop('selected', true);
                    }
                    else {
                        $('#role_select option[value=' + role_id + ']').prop('selected', false).prop('selected', true);
                    }
                    $('input[name="roamTaskPeople"][value=' + approvalType + ']').prop('checked', true);

                    //}


                    //在勾选前初始化一下
                    initialCheckbox();

                    //将勾选的再次选中，填写真实数据
                    fillNodeFrom(activeId);

                    ajaxModal(url, function () {
                        //popup.Message("T",'加载完成执行')
                    });
                },
            }
            , fnRepeat: function () {
                //popup.Message("T","步骤连接重复1");//可使用 jquery ui 或其它方式提示
                mAlert("步骤连接重复了，请重新连接");

            }
            , fnClick: function () {
                var activeId = _canvas.getActiveId();
            }
            , fnDbClick: function () {
                var activeId = _canvas.getActiveId();//右键当前的ID
                /*重要提示 start*/
                /*popup.Message("T","这里要使用程序处理，并非简单html页面，如果无法显示，请建立虚拟站点");*/
                /*重要提示 end */
                //var url = "/index.php?s=/Flowdesign/attribute/id/"+activeId+".html";
                var url = '/ks_manager/login/attribute.html?id=' + activeId;
                var process_name = $("#window" + activeId).find('.text').text();
                var role_id = $("#window" + activeId).attr('role_id');
                var approvalType = $("#window" + activeId).attr('approvalType') ? $("#window" + activeId).attr('approvalType') : '1';
                //初始化弹框里的值
                /*if(products[activeId]){
                    var v = products[activeId];
                    $("#process_name").val(v.node_name);
                    $('#role_select option[value=' + v.role_id + ']').attr('selected',false).attr('selected',true);
                }else{*/
                $("#process_name").val(process_name);
                if (!role_id) {
                    $('#role_select option').eq(0).prop('selected', false).prop('selected', true);
                }
                else {
                    $('#role_select option[value=' + role_id + ']').prop('selected', false).prop('selected', true);
                }
                //}
                $('input[name="roamTaskPeople"][value=' + approvalType + ']').prop('checked', true);


                //在勾选前初始化一下
                initialCheckbox();

                //将勾选的再次选中，填写真实数据
                fillNodeFrom(activeId);

                ajaxModal(url, function () {
                    //popup.Message("T",'加载完成执行')
                });
            }
        });


    /*保存*/
    $("#leipi_save").on('click', function () {
        var ProcessInfo = _canvas.getProcessInfo(product_id, workflow_id, product_name);
        var processInfo = ProcessInfo;//连接信息

        var url = "/index.php?s=/Flowdesign/save_canvas.html";
        $.post(url, {"flow_id": the_flow_id, "process_info": processInfo}, function (data) {
            mConstant.fn.Message("F", data.msg);
        }, 'json');
    });
    /*清除*/
    $("#leipi_clear").bind('click', function () {
        if (_canvas.clear()) {
            popup.Message("T", "清空连接成功，你可以重新连接");
            //mAlert("");
        } else {
            popup.Message("F", "清空连接失败");
            //mAlert("清空连接失败");
        }
    });

    //更改属性或权限取得的name和roleID
    $("#attributeOK").on('click', function () {
        var activeId = _canvas.getActiveId();
        var node_name = $("#process_name").val();
        var role_id = $("#role_select option:selected").val();
        var approvalType = $("input[name='roamTaskPeople']:checked").val();
        /*if(!role_id){
            popup.Message("T",'请选择角色');
            return false;
        }*/
        var ProcessInfo = _canvas.getProcessInfo(product_id, workflow_id, product_name);
        $.each(ProcessInfo["nodeList"], function (index, value) {
            if (activeId == value.id) {
                value.node_name = node_name;
                value.role_id = role_id;
                value.approvalType = parseInt(approvalType);
                $.ajax({
                    url: urlHeader + "updateNodeById.do",
                    type: 'POST',
                    crossDomain: true,
                    xhrFields: {
                        withCredentials: true
                    },
                    data: {frontData: JSON.stringify(value)},
                    success: function (data) {
                        data = JSON.parse(data)
                        $("#window" + activeId).find('.text').text(node_name);
                        $("#window" + activeId).attr('role_id', role_id);
                        $("#window" + activeId).attr('approvalType', approvalType);
                    }
                })
            }
        });

        var nodeFromInfos = new Array();

        $.each($(".customShow:checked"), function (i, e) {
            if ($(e).attr('fixed_name')) {
                var is_edit = $(e).parents('tr').find('.edit:checked').length ? 1 : 2;
                if ($(e).data('type') == 2 || $(e).data('type') == 4) {
                    var obj = {
                        node_id: activeId,
                        is_edit: is_edit,
                        type: $(e).data('type'),
                        define_id: $(e).attr('define_id'),
                        fixed_name: $(e).attr('fixed_name')
                    }
                }
                if ($(e).data('type') == 1) {
                    var obj = {
                        node_id: activeId,
                        is_edit: is_edit,
                        type: $(e).data('type'),
                        fixed_key: $(e).attr('define_id'),
                        fixed_name: $(e).attr('fixed_name')
                    }
                }
                nodeFromInfos.push(obj);
            }
        })

        $.ajax({
            url: urlHeader + urlList.insertNodeFromInfo,
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            data: {
                frontData: JSON.stringify({
                    node_id: activeId,
                    nodeFromInfos: nodeFromInfos
                })
            },
            type: "POST",
            success: function (data) {
                data = JSON.parse(data)
                if (data.type == 1) {
                    popup.Message('T', data.msg)
                } else {
                    popup.Message('F', data.msg)
                }
                /*location.href="/ks_manager/order.html";*/
            }
        })

        ProcessInfo = JSON.stringify(ProcessInfo);
        attributeModal.modal('toggle');
    })


    $('#attributeTab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    })


    $("#leipi_add").on('click', function () {
        var mLeft = parseInt($("#jqContextMenu").css("left")),
            mTop = parseInt($("#jqContextMenu").css("top"));

        /*重要提示 start*/
        /*
                            popup.Message("T","这里使用ajax提交，请参考官网示例，可使用Fiddler软件抓包获取返回格式");
        */
        var style = "width:121px;height:41px;line-height:41px;color:#0e76a8;left:" + mLeft + "px;top:" + mTop + "px;";
        $.ajax({
            url: urlHeader + "insertNodeInfo.do",
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            data: {style: style, workflow_id: workflow_id, product_id: product_id},
            type: 'POST',
            //将修改的样式以及查询返回的数据传入addProcess
            success: function (data) {
                _canvas.addProcess(JSON.parse(data), style)
            }
        });
    })

})
    ;

    $.ajax({
        url: urlHeader + "selectRoleList.do",
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        success: function (data) {
            data = JSON.parse(data)
            $.each(data.content, function (index, item) {
                $('#role_select').append("<option value='" + item.id + "'>" + item.roleName + "</option>");
            })
        }
    });

//渲染出节点表单
    $.ajax({
        url: urlHeader + urlList.queryAllFormFields,
        type: "POST",
        crossDomain: true,
        xhrFields: {
            withCredentials: true
        },
        data: {
            product_id: getAurlparam('productId')
        },

        success: function (data) {
            data = JSON.parse(data)
            //固定字段渲染
            if (data.content.orderInfos) {
                $.each(data.content.orderInfos, function (i, e) {
                    $("#nodeForm").append("<tr><th>" + e.column_name + "</th><td></td><td><label class=\"checkbox\"><input type=\"checkbox\" class=\"customShow\" define_id=\"" + e.column_key + "\" fixed_name=\"" + e.column_name + "\" data-type=\"1\" ></label></td><td><label class=\"checkbox\"><input type=\"checkbox\" class='edit' disabled></label></td></tr>");
                })
            }

            //扣费明细字段渲染
            if (data.content.productFeeInfos) {
                $.each(data.content.productFeeInfos, function (i, e) {
                    $("#nodeForm").append("<tr><th>" + e.fee_name + "</th><td></td><td><label class=\"checkbox\"><input type=\"checkbox\" class=\"customShow\" define_id=\"" + e.fee_id + "\" fixed_name=\"" + e.fee_name + "\" data-type=\"4\" ></label></td><td><label class=\"checkbox\"><input type=\"checkbox\" class='edit' disabled></label></td></tr>");
                })
            }

            //自定义字段渲染
            if (data.content.productProperty) {
                $.each(data.content.productProperty, function (i, e) {
                    $("#nodeForm").append("<tr class='parent" + i + "' tr_id='" + i + "'><th><button class='col btn-info'  state='close'>+</button>" + e.type_name + "</th><td></td><td><label class=\"checkbox\"><input type=\"checkbox\" class=\"customShow\" define_id=\"" + e.id + "\" data-type=\"2\" ></label></td><td><label class=\"checkbox\"><input type=\"checkbox\" class='edit' disabled></label></td></tr><tr tr_id='tabel_" + i + "'><td colspan='16'><table class='table table-condensed table-bordered table-hover inner_table" + i + "'></table></td></tr>");
                    $.each(e.productPropertyDefines, function (ii, ee) {
                        if (ee.type != 'form_name') {
                            $(".inner_table" + i).append("<tr><th>" + ee.name + "</th><td></td><td><label class=\"checkbox\"><input type=\"checkbox\" class=\"customShow\" define_id=\"" + ee.id + "\" fixed_name=\"" + ee.name + "\" data-type=\"2\" ></label></td><td><label class=\"checkbox\"><input type=\"checkbox\" class='edit' disabled></label></td></tr>");
                        }
                    })
                })
            }

            //拿到所有的复选框，当有复选框没选上的时候,取消全选
            $(".customShow").on('click', function () {
                var edit = ($(this).parents('td').siblings('td').find('.edit'))
                if ($(this).is(':checked')) {
                    edit.prop('disabled', false);
                } else {
                    edit.prop('disabled', true).prop('checked', false);
                }

                var checkboxs = $(".customShow");
                var sum = 0;
                var length = checkboxs.length;
                $.each(checkboxs, function (i, checkbox) {
                    if ($(checkbox).prop("checked")) {
                        sum++;
                    }
                })
                if (sum == length) {
                    $('.show').prop("checked", true);
                } else {
                    $('.show').prop("checked", false);
                }
            })

            //拿到所有的复选框，当有复选框没选上的时候,取消全选
            $(".edit").on('click', function () {
                var checkboxs = $(".edit");
                var sum = 0;
                var length = checkboxs.length;
                $.each(checkboxs, function (i, checkbox) {
                    if ($(checkbox).prop("checked")) {
                        sum++;
                    }
                })
                if (sum == length) {
                    $('.write').prop("checked", true);
                } else {
                    $('.write').prop("checked", false);
                }
            })

            $('.col').click(function () {   // 获取所谓的父行
                var $this = $(this).parents("tr");
                if ($(this).attr("state") == "close") {
                    $(this).attr("state", "open");
                    $(this).html('-')
                } else if ($(this).attr("state") == "open") {
                    $(this).attr("state", "close");
                    $(this).html('+')
                }
                var name = $this.attr("class");
                var tr_id = $this.attr("tr_id");

                $this.nextAll("tr[tr_id=tabel_" + tr_id + "]").toggle();   // 隐藏/显示所谓的子行
            });

        }
    });

// 全选
    $(".show").click(function () {
        $(".customShow").prop('checked', $(this).prop('checked'))
        if ($(this).is(':checked')) {
            $('.write').prop('disabled', false);
        }
        else {
            $('.write').prop('disabled', true);
        }
        $('.edit').prop('disabled', $('.write').prop('disabled'))
    })


    $(".write").on("click", function () {
        $(".edit").prop('checked', $(this).prop('checked'))
    })

    $(document).ajaxStart(function () {
        $("#loading", parent.document).show();
    })

    $(document).ajaxStop(function () {
        $("#loading", parent.document).hide();
    })








